package com.atguigu.ad.flume.interceptor;

import org.apache.flume.Context;
import org.apache.flume.Event;
import org.apache.flume.interceptor.Interceptor;


import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 时间戳拦截器（解决零点漂移）+ETL清洗
 */

public class TimestampInterceptor implements Interceptor {

    private Pattern compile;

    @Override
    public void initialize() {
//        正则表达式，匹配   t=1673078178498
        compile = Pattern.compile(".*t=(\\d{13}).*");
    }

    @Override
    public Event intercept(Event event) {
/**
 * 数据格式：
 *      "2023-01-07T15:56:19.226""GET""/ad/tencent/impression?id=57&t=1673078178498&ip=101.110.126.207&ua=Mozilla/5.0%20(Windows;%20U;%20Windows%20NT%206.1;%20en-AU;%20rv:1.9.2.14)%20Gecko/20110218%20Firefox/3.6.14&device_id=c7a6c00fbd61490e818a49562e99456f&os_type=android""200""103.125.199.121"
 */
        byte[] body = event.getBody();
        String logString = new String(body, StandardCharsets.UTF_8);
//        去掉两端的双引号
        String substring = logString.substring(1, logString.length()-1);
//        去掉中间的双引号
        String u0001 = substring.replaceAll("\"\u0001\"", "\u0001");

//        获取到 t=1673078178498
//        提取时间戳
        Matcher matcher = compile.matcher(u0001);
        if(matcher.matches()){
            String group = matcher.group(1);
//            解决零点漂移
            event.getHeaders().put("timestamp",group);
        }else {
            return null;
        }
        event.setBody(u0001.getBytes(StandardCharsets.UTF_8));

        return event;
    }

    @Override
    public List<Event> intercept(List<Event> list) {
/**
 * list去调用单个event方法
 */
        Iterator<Event> iterator = list.iterator();
        while (iterator.hasNext()){
            Event next = iterator.next();
            Event intercept = intercept(next);
            if(intercept == null){
                iterator.remove();
            }
        }
        return list;
    }

    @Override
    public void close() {

    }
    public static class Builder implements Interceptor.Builder{


        @Override
        public Interceptor build() {
            return new TimestampInterceptor();
        }

        @Override
        public void configure(Context context) {

        }
    }


}

